<template>
	<div class="recent-tasks-container" v-loading.fullscreen.lock="fullscreenLoading">
		<div style="margin: 2% auto">
			<el-divider content-position="center"><h1>任务看板</h1></el-divider>
		</div>
		<div class="header">
			<el-input v-model="searchQuery" placeholder="任务名称" class="search-bar" suffix-icon="el-icon-search" @change="filterTasks"></el-input>
			<el-select v-model="selectedStatus" placeholder="选择状态" class="status-filter" @change="filterTasks">
				<el-option label="选择状态" value=""></el-option>
				<el-option label="已完成" value="completed"></el-option>
				<el-option label="进行中" value="in-progress"></el-option>
				<el-option label="错误" value="error"></el-option>
			</el-select>
			<el-select v-model="selectedAIModel" placeholder="选择AI模型" class="ai-model-filter" @change="filterTasks">
				<el-option label="选择AI模型" value=""></el-option>
				<el-option v-for="model in aiModels" :key="model.model_id" :label="model.model_name" :value="model.model_id">
					{{ model.model_name }}: {{ model.model_description }}
				</el-option>
			</el-select>
			<el-select v-model="selectedLibrary" placeholder="选择筛选库" class="library-filter" @change="filterTasks">
				<el-option label="选择筛选库" value=""></el-option>
				<el-option v-for="library in libraries" :key="library.library_id" :label="library.library_name" :value="library.library_id">
					{{ library.library_name }}: {{ library.library_description }}
				</el-option>
			</el-select>
			<el-date-picker
				v-model="selectedDate"
				type="daterange"
				range-separator="至"
				start-placeholder="开始日期"
				end-placeholder="结束日期"
				@change="filterTasks"
			></el-date-picker>
		 <i class="el-icon-refresh refresh-icon" @click="refreshPage" style="cursor: pointer;"></i>
		</div>
		<div class="tasks-grid" v-if="filteredTasks.length > 0">
			<el-row :gutter="30">
				<el-col :span="8" v-for="task in paginatedTasks" :key="task.id" style="margin-bottom: 30px">
					<el-card class="task-card" shadow="hover">
						<div style="display: flex; justify-content: space-between; align-items: center; font-size: 12px">
							<span>smart-drug-finder</span>
							<div style="display: flex; align-items: center">
								<!-- 动态状态点 -->
								<div :style="{ width: '8px', height: '8px', backgroundColor: taskStatusColor(task.task_status), borderRadius: '50%', marginRight: '5px' }"></div>
								<!-- 状态文本 -->
								<span>{{ taskStatusText(task.task_status) }}</span>
								<!-- 动态时间 -->
								<span class="time" style="margin-left: 10px">{{ formattedTime(task) }}</span>
							</div>
						</div>

						<div class="task-details">
							<p class="task-name">
								<strong>任务名称:</strong>
								{{ task.task_name }}
							</p>
							<p class="task-info">
								<strong>所选模型:</strong>
								{{ getModelName(task.model_id) }}
							</p>
							<p class="task-info">
								<strong>筛选库:</strong>
								{{ getLibraryName(task.library_id) }}
							</p>
							<p class="task-info">
								<strong>提交时间:</strong>
								{{ task.create_time }}
							</p>
						</div>
						<div class="task-actions">
							<el-button type="text" size="medium" @click="viewDetails(task)">任务详情</el-button>
							<el-button type="text" size="medium" style="color: #f56c6c" @click="deleteTask(task)">删除任务</el-button>
						</div>
					</el-card>
				</el-col>
			</el-row>
		</div>
		<el-empty v-else description="暂无任务，请创建一个新任务。"></el-empty>
		<div class="pagination" v-if="filteredTasks.length > 0">
			<el-pagination
				@current-change="handlePageChange"
				:current-page="currentPage"
				:page-size="pageSize"
				:page-sizes="[3, 6, 9]"
				layout="sizes, prev, pager, next, jumper"
				:total="filteredTasks.length"
				@size-change="handleSizeChange"
			></el-pagination>
		</div>
	</div>
</template>

<script>
import axios from 'axios';
import { Message, MessageBox } from 'element-ui';

export default {
	name: 'RecentTasksView',
	data() {
		return {
			searchQuery: '',
			selectedStatus: '',
			selectedDate: [],
			selectedAIModel: '',
			selectedLibrary: '',
			currentPage: 1,
			pageSize: 6,
			tasks: [],
			aiModels: [],
			libraries: [],
			fullscreenLoading: false // 控制加载遮罩的显示
		};
	},
	computed: {
		filteredTasks() {
			let filtered = this.tasks;
			if (this.searchQuery) {
				filtered = filtered.filter((task) => task.task_name.includes(this.searchQuery));
			}
			if (this.selectedStatus) {
				filtered = filtered.filter((task) => task.task_status === this.selectedStatus);
			}
			if (this.selectedDate.length === 2) {
				const [startDate, endDate] = this.selectedDate;
				filtered = filtered.filter((task) => {
					const submittedDate = new Date(task.create_time);
					return submittedDate >= new Date(startDate) && submittedDate <= new Date(endDate);
				});
			}
			if (this.selectedAIModel) {
				filtered = filtered.filter((task) => task.model_id === this.selectedAIModel);
			}
			if (this.selectedLibrary) {
				filtered = filtered.filter((task) => task.library_id === this.selectedLibrary);
			}
			return filtered;
		},
		paginatedTasks() {
			const start = (this.currentPage - 1) * this.pageSize;
			const end = start + this.pageSize;
			return this.filteredTasks.slice(start, end).slice(0, this.pageSize);
		}
	},
	methods: {
		    refreshPage() {
	
		this.fetchTasks();
		this.fetchAIModels();
		this.fetchLibraries();
		    },
		// 根据任务状态返回状态点颜色
		taskStatusColor(status) {
			switch (status) {
				case 'in-progress':
					return '#00d8ff'; // 蓝色表示运行中
				case 'completed':
					return '#67c23a'; // 绿色表示已完成
				case 'error':
					return '#f56c6c'; // 红色表示失败
				default:
					return '#909399'; // 灰色表示未知状态
			}
		},
		// 根据任务状态返回文本
		taskStatusText(status) {
			switch (status) {
				case 'in-progress':
					return '运行中';
				case 'completed':
					return '已完成';
				case 'error':
					return '失败';
				default:
					return '未知状态';
			}
		},
		calculateElapsedTime(endTime, startTime) {
			const diffMs = endTime - startTime; // 计算时间差，单位为毫秒
			const diffSec = Math.floor(diffMs / 1000); // 转换为秒
			const hours = Math.floor(diffSec / 3600); // 小时
			const minutes = Math.floor((diffSec % 3600) / 60); // 分钟
			const seconds = diffSec % 60; // 秒

			// 如果时间差超过1小时，显示00:00:00格式，否则显示00:00格式
			if (hours > 0) {
				return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
			} else {
				return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
			}
		},

		// 格式化时间
		formattedTime(task) {
			const status = task.task_status; // 任务状态
			const createTime = new Date(task.create_time.replace('GMT', '+08:00')); // 任务创建时间 
			const now = new Date(Date.now()); // 当前时间
			if (status === 'in-progress') {
				// 任务正在运行，用当前时间减去创建时间
				return this.calculateElapsedTime(now, createTime);
			} else if (status === 'completed' && task.complete_time) {
				// 任务已完成，用完成时间减去创建时间
				const completeTime = new Date(task.complete_time.replace('GMT', '+08:00')); // 任务完成时间 
				return this.calculateElapsedTime(completeTime, createTime);
			} else if (status === 'error') {
				// 任务出错，返回空
				return '';
			} else {
				return 'N/A'; // 如果状态不明确，返回N/A
			}
		},

		async fetchTasks() {
			try {
				this.fullscreenLoading = true;
				const response = await axios.get('/api/tasks/search', { params: { user_id: 1 } });
				this.tasks = response.data;
			} catch (error) {
				Message.error('获取任务列表失败');
			} finally {
				this.fullscreenLoading = false;
			}
		},
		async fetchAIModels() {
			try {
				this.fullscreenLoading = true;
				const response = await axios.get('/api/models');
				this.aiModels = response.data;
			} catch (error) {
				Message.error('获取AI模型列表失败');
			} finally {
				this.fullscreenLoading = false;
			}
		},
		async fetchLibraries() {
			const userId = 1;
			try {
				this.fullscreenLoading = true;
				const response = await axios.get('/api/libraries', {
					params: {
						user_id: userId
					}
				});
				this.libraries = response.data;
			} catch (error) {
				Message.error('获取筛选库列表失败');
			} finally {
				this.fullscreenLoading = false;
			}
		},
		async deleteTask(task) {
			try {
				this.fullscreenLoading = true;
				await MessageBox.confirm('确定要删除这个任务吗？', '警告', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(async () => {
					try {
						await axios.delete(`/api/tasks/${task.task_id}`);
						Message.success('任务删除成功');
						this.fetchTasks(); // 更新任务列表
					} catch (error) {
						Message.error('删除任务失败');
					}
				})
				.catch(() => {});
			} catch (error) {
				Message.error('删除任务失败');
			} finally {
				this.fullscreenLoading = false;
			}
		},
		getModelName(model_id) {
			const model = this.aiModels.find((m) => m.model_id === model_id);
			return model ? model.model_name : '未知模型';
		},
		getLibraryName(library_id) {
			const library = this.libraries.find((l) => l.library_id === library_id);
			return library ? library.library_name : '未知库';
		},
		filterTasks() {
			this.currentPage = 1;
		},
		handlePageChange(page) {
			this.currentPage = page;
		},
		handleSizeChange(size) {
			this.pageSize = size;
			this.currentPage = 1;
		},
		viewDetails(task) {
			this.$router.push({ name: 'TaskDetails', params: { taskId: task.task_id } });
		}
	},
	created() {
		this.fetchTasks();
		this.fetchAIModels();
		this.fetchLibraries();
	}
};
</script>

<style scoped>
.recent-tasks-container {
	padding: 20px;
	font-family: Arial, sans-serif;
}
.header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin: 2.5% auto;
	flex-wrap: wrap;
}
.search-bar {
	max-width: 30%;
}
.filter-controls {
	display: flex;
	gap: 10px;
	flex-wrap: wrap;
}
.tasks-grid {
}
.task-card {
	border-radius: 8px;
	box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
	background-color: #ffffff;
	transition: transform 0.3s;
}
.task-card:hover {
	transform: translateY(-5px);
}
.task-details {
	margin-bottom: 20px;
}
.task-name {
	text-align: left;
	font-size: 14px;
	font-weight: bold;
	margin-top: 20px;
	margin-bottom: 25px;
}
.task-info {
	text-align: left;
	font-size: 14px;
}
.task-actions {
	display: flex;
	justify-content: space-between;
	margin-top: 20px;
}
.pagination {
	margin-top: 20px;
	text-align: center;
}
</style>
